// pages/kitchen/kitchen.js
const kitchenService = require('../../services/kitchenService')

const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    showModal: false,
    kitchen: null,
    dishes: [],
    loading: true,
    showDeleteModal: false,
    dishToDelete: null,
    showShareModal: false,  // 添加分享弹窗状态
    // 标签相关数据
    currentTag: 'all',
    tagList: [],
    tagStats: {},
    filteredDishes: [],
    theme: ''  // 添加主题数据
  },

  /**
   * 导航到菜品详情
   */
  navigateToDishDetail(e) {
    const dishId = e.currentTarget.dataset.id;
    if (this.data.kitchen) {
      console.log('厨房页查看菜品详情:', dishId);
      wx.navigateTo({
        url: `/pages/dish-detail/dish-detail?kitchenId=${this.data.kitchen._id}&dishId=${dishId}`,
        events: {
          // 监听菜品更新事件（如果在详情页面有编辑功能）
          dishUpdated: (data) => {
            console.log('菜品从详情页更新，刷新数据:', data);
            // 重新加载厨房数据
            this.loadKitchenData(this.data.kitchen._id);
          }
        }
      });
    }
  },

  /**
   * 处理标签数据，统计每个标签的菜品数量并排序
   */
  processTagsData(dishes) {
    // 如果没有菜品，设置空数据并返回
    if (!dishes || dishes.length === 0) {
      this.setData({
        tagList: [],
        tagStats: {},
        filteredDishes: []
      });
      return;
    }
    
    // 计算每个标签的菜品数量
    const tagStats = {};
    let untaggedCount = 0;
    
    dishes.forEach(dish => {
      // 确保tags是数组
      const tags = dish.tags || [];
      
      if (tags.length === 0) {
        // 计算未分类菜品数量
        untaggedCount++;
      } else {
        // 统计每个标签的出现次数
        tags.forEach(tag => {
          if (tagStats[tag]) {
            tagStats[tag]++;
          } else {
            tagStats[tag] = 1;
          }
        });
      }
    });
    
    // 记录未分类的菜品数量
    tagStats['未分类'] = untaggedCount;
    
    // 将标签转换为数组并按菜品数量排序
    const tagList = Object.keys(tagStats)
      .filter(tag => tag !== '未分类') // 排除未分类标签，因为它会单独显示
      .map(tag => ({ tag, count: tagStats[tag] }))
      .sort((a, b) => b.count - a.count); // 按数量降序排序
    
    // 设置相关数据
    this.setData({
      tagList,
      tagStats,
      filteredDishes: this.filterDishesByTag(dishes, this.data.currentTag)
    });
  },
  
  /**
   * 根据标签筛选菜品
   */
  filterDishesByTag(dishes, tag) {
    if (tag === 'all') {
      return dishes;
    } else if (tag === '未分类') {
      return dishes.filter(dish => !dish.tags || dish.tags.length === 0);
    } else {
      return dishes.filter(dish => dish.tags && dish.tags.includes(tag));
    }
  },
  
  /**
   * 标签选择处理
   */
  selectTag(e) {
    const tag = e.currentTarget.dataset.tag;
    
    this.setData({
      currentTag: tag,
      filteredDishes: this.filterDishesByTag(this.data.dishes, tag)
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取当前主题
    const theme = wx.getStorageSync('theme') || 'theme-green';
    this.setData({ theme });
    
    this.setData({ loading: true });
    
    // 检查登录状态
    if (!app.checkLoginStatus()) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 如果指定了厨房ID，则加载该厨房
    // 如果没有指定厨房ID，则获取默认厨房
    const kitchenId = options.id;
    
    console.log('kitchen.js onLoad - 页面参数:', options);
    this.loadKitchenData(kitchenId);
    

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 检查主题是否有变化
    const theme = wx.getStorageSync('theme');
    if (theme !== this.data.theme) {
      this.setData({ theme });
    }
    
    // 检查登录状态
    if (!app.checkLoginStatus()) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    this.loadKitchenData(kitchenId);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    
  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    
  },

  /**
   * 显示分享选项
   */
  shareKitchen() {
    this.setData({
      showShareModal: true
    });
  },

  /**
   * 隐藏分享选项
   */
  hideShareOptions() {
    this.setData({
      showShareModal: false
    });
  },


  /**
   * 用户点击右上角分享（或点击分享给微信好友）
   */
  onShareAppMessage() {
    const kitchen = this.data.kitchen || {};
    return {
      title: `${kitchen.name || '我的厨房'}`,
      path: `/pages/kitchen/kitchen?id=${kitchen._id}`,
      imageUrl: kitchen.image || '/imgs/chef-hat.svg'
    };
  },

 /**
  * 加载厨房数据
  * @param {*} kitchenId 
  * @returns 
  */
  loadKitchenData: function(kitchenId) {
    if (!kitchenId) return;
    
    // 显示加载提示
    wx.showLoading({
      title: '加载中...'
    });

    this.setData({ loading: true });
    
    Promise.all([
      kitchenService.getKitchenById(kitchenId),
      kitchenService.getDishesForKitchen(kitchenId)
    ]).then(([kitchen, dishes]) => {
      this.setData({
        kitchen: kitchen,
        dishes: dishes,
        loading: false
      });
      
      // 处理标签统计
      this.processTagsData(dishes);
      wx.hideLoading();
    }).catch(err => {
      console.error('加载厨房数据失败', err);
      wx.hideLoading();
      wx.showToast({
        title: '加载数据失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    });
  },

  
  showDeleteDishModal: function(e) {
    const dishId = e.currentTarget.dataset.id;
    const dish = this.data.dishes.find(d => d._id === dishId);
    
    this.setData({
      showDeleteModal: true,
      dishToDelete: dish
    });
  },
  
  hideDeleteModal: function() {
    this.setData({
      showDeleteModal: false,
      dishToDelete: null
    });
  }
  
}) 